package com.example.test622.login;

import android.widget.Toast;
import com.example.common.mvi.BaseView;
import com.example.test622.databinding.ActivityLoginAactivity2Binding;
import com.tencent.mmkv.MMKV;
import java.util.HashMap;
import java.util.Map;

public class LoginAActivity extends BaseView<ActivityLoginAactivity2Binding, LoginViewModel> {
    private Map<String, String> map = new HashMap<>();
    {
        map.put("password", "123");
        map.put("username", "chen");
    }
    @Override
    public void initView() {
        getBinding().setUser(map);
        getBinding().btn.setOnClickListener(v -> {
            String password = map.get("password");
            String username = map.get("username");
            assert password != null;
            assert username != null;
            LoginIntent loginIntent = new LoginIntent.Login(password, username);
            getViewModel().getIntent().send(loginIntent, null);
        });
    }
    @Override
    public void initData() {
        getViewModel().getState().observe(this, state -> {
            if (state instanceof LoginState.LoginSuccess) {
                MMKV mmkv = MMKV.defaultMMKV();
                mmkv.encode("token", ((LoginState.LoginSuccess) state).getUser().getData().getToken());
            }else if (state instanceof LoginState.LoginFailed){
                Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT);
            }
        });
    }
}